import {AfterViewInit, Component, OnInit, ViewChild} from '@angular/core';
import {AlertComponent, AlertOptions, ApiService, deepCopy, getProperty, MessageService, ModalComponent, PaginationService, ProgressBarService, Table} from '../../../../../ng-tools';
import {TicketService} from '../../../../services/api/ticket.service';
import {NavigationExtras, Router} from '@angular/router';
import {RobotGroupFormatterService} from '../../../../services/formatter/robot-group-formatter.service';
import {HttpParams} from '@angular/common/http';
import {MoneyRecordFormatterService} from '../../../../services/formatter/money-record-formatter.service';
import {SystemGroupFormatterService} from '../../../../services/formatter/system-group-formatter.service';
import {StatusPipe} from '../../../../../ng-tools/src/components/badge/status.pipe';

@Component({
  selector: 'system-group',
  templateUrl: './game-group.component.html',
  styleUrls: ['./game-group.component.scss'],
  providers: [PaginationService, ApiService, StatusPipe]
})
export class GameGroupComponent implements OnInit, AfterViewInit {
  @ViewChild('modal') modal: ModalComponent;
  breadcrumb = [
    {name: '游戏群', cssIcon: 'fa fa-fw fa-gamepad'}
  ];
  @ViewChild('alert') alert: AlertComponent;
  alertOptions: AlertOptions = {
    theme: 'danger',
    data: null,
    position: 'center'
  };
  currentRowIndex;
  handleData;
  page = 1;
  editGroupData;
  buttons = [];
  moneyTable = new Table({
    headers: this.moneyFormatter.formatter,
  });

  constructor(private message: MessageService,
              private ticketService: TicketService,
              public pagination: PaginationService,
              private router: Router,
              private moneyFormatter: SystemGroupFormatterService) {
  }
  ngOnInit() {
    this.getInfo(1);
  }
  get getProperty() {
    return getProperty;
  }
  btnClicked(e, btnIndex, rowIndex) {
    this.currentRowIndex = rowIndex;
    const data = this.pagination.page.results[rowIndex];
    const func = this.buttons[rowIndex][btnIndex].click;
    e.stopPropagation();
    if (typeof func === 'function') {
      this.buttons[rowIndex][btnIndex].click(data, rowIndex);
    }
  }
  showAddOrEditModal() {
    const navigationExtras: NavigationExtras = {
      queryParams: { 'gameGroup': JSON.stringify(this.editGroupData) },
    };
    this.router.navigate(['main/oplatform/game-group-config'], navigationExtras).catch();
  }
  showFreezeModal(item: any) {
    const options = {
      id: 'freezeGroup',
      title: '冻结群',
      cssIcon: 'fa fa-fw fa-warning',
      size: 'sm',
      theme: 'danger',
      backdrop: 'static',
      data: '是否冻结该群？',
      closeBtn: true,
      confirmBtn: true
    };
    this.modal.show(options);
    this.handleData = item;
  }
  showCanceFreezelModal(item: any) {
    const options = {
      id: 'cancleFreezeGroup',
      title: '解冻群',
      cssIcon: 'fa fa-fw fa-warning',
      size: 'sm',
      theme: 'danger',
      backdrop: 'static',
      data: '是否解冻该群？',
      closeBtn: true,
      confirmBtn: true
    };
    this.modal.show(options);
    this.handleData = item;
  }
  getInfo(page) {
    this.buttons = [];
    this.pagination.simpleFormatter = this.moneyTable.options.headers;
    this.ticketService.get(this.ticketService.urls.getGameGroup, {
      observe: 'response',
      params: new HttpParams()
          .append('web_token', localStorage.getItem('token'))
          .append('type', '1')
          .append('pageNum', page + '')
          .append('pageSize', '10')}).subscribe((resp) => {
      if (resp.body.success) {
        const result = resp.body.returnValue.page;
        const paginationResult = [];
        for (const item of result.list) {
          item.userImage = this.ticketService.serverConfig.httpServer + this.ticketService.baseUrl + this.ticketService.urls.GroupAvatarDownloader + '?action=ad&g_id=' + item.gid + '&enforceDawnload=1';
          paginationResult.push(item);
        }
        this.pagination.page.results = paginationResult;
        this.pagination.page.totalPage = result.pages;
        this.pagination.page.pageNumber = result.pageNum;
        this.pagination.page.pageSize = result.pageSize;
        this.pagination.formatData();
        /** 绑定事件 */
        this.pagination.dataLoadSubscriber$.subscribe(() => {
          for (const item of this.pagination.page.results) {
            let buttonItem = [];
              if (item.status === 1) {
                buttonItem = [
                  {
                    btnClass: 'btn-success p-1',
                    text: '编辑',
                    isShow: true,
                    click: (e) => {
                      this.editGroupData = e;
                      this.showAddOrEditModal();
                    }
                  },
                  {
                    btnClass: 'btn-danger p-1',
                    text: '冻结',
                    isShow: true,
                    click: (e) => {
                      this.showFreezeModal(e);
                    }
                  },
                ];
              }
              if (item.status === -2) {
                buttonItem = [
                  {
                    btnClass: 'btn-success p-1',
                    text: '编辑',
                    isShow: true,
                    click: (e) => {
                      this.editGroupData = e;
                      this.showAddOrEditModal();
                    }
                  },
                  {
                    btnClass: 'btn-warning p-1',
                    text: '解冻',
                    isShow: true,
                    click: (e) => {
                      this.showCanceFreezelModal(e);
                    }
                  },
                ];
              }
            this.buttons.push(buttonItem);
          }
          this.message.sendMessage('page load progress', this);
        });
      } else {
        this.router.navigateByUrl('/login').catch();
      }
    });
  }
  firstPage() {
    this.page = 1;
    this.getInfo(1);
  }
  previousPage() {
    if (this.page > 1) {
      this.page = this.page - 1;
    } else {
      this.page = 1;
    }
    this.getInfo(this.page);
  }
  nextPage() {
    if (this.page < this.pagination.page.totalPage) {
      this.page = this.page + 1;
    } else {
      this.page = this.pagination.page.totalPage;
    }
    this.getInfo(this.page);
  }
  lastPage() {
    this.page = this.pagination.page.totalPage;
    this.getInfo(this.pagination.page.totalPage);
  }
  freezeAndCancle(freeze) {
    this.ticketService.post(this.ticketService.urls.freezeGroup, {gId: this.handleData.gid, status: freeze}, {
      observe: 'response',
      params: new HttpParams().append('web_token', localStorage.getItem('token'))}).subscribe((resp) => {
      if (resp.body.success) {
        this.getInfo(this.page);
      }
    });
  }
  ngAfterViewInit(): void {
    this.modal.event.subscribe({
      next: (event) => {
        if (event.name === 'confirm' && event.id === 'freezeGroup') {
          this.modal.hide();
          this.freezeAndCancle(-2);
        }
        if (event.name === 'confirm' && event.id === 'cancleFreezeGroup') {
          this.modal.hide();
          this.freezeAndCancle(1);
        }
      }
    });
    this.message.sendMessage('page load progress', this, '300ms');
    this.message.sendMessage('breadcrumb changed', this, this.breadcrumb);
  }
}
